<?php
namespace app\common\service\SystemConfigService\Channel;

use app\Normal;
use app\model\BbcModel\ConfigChannel;
use app\model\BbcModel\Manager;
use app\model\BbcModel\ChannelWx;
/*
 * @author banban
 * @datetime 2022-8-5 14:27:02
 * @copyright 板板<249366615@qq.com>
 * @filename ChannelConfigService
 */
class ChannelConfigService
{
    /**
     * 获取渠道配置列表
     * @param array $param
     * @return array
     */
    public function getConfigListByPage(array $param):array {
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:20;
        if (empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'cid必传');
        }
        $where = [
            ['cid', '=', $param['cid']]
        ];
        //查询条件
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!empty($param['name'])) {
            $where[] = ['name', 'like', "%{$param['name']}%"];
        }
        if (!empty($param['cd_start'])) {
            $where[] = ['md', '>=', strtotime($param['cd_start'])];
        }
        if (!empty($param['cd_end'])) {
            $where[] = ['md', '<=', strtotime($param['cd_end'])];
        }
        if (isset($param['status']) && $param['status'] !== '') {
            $where[] = ['status', '=', $param['status']];
        }
        if (isset($param['type']) && $param['type'] != '') {
            $where[] = ['type', '=', $param['type']];
        }
        if (isset($param['is_config']) && $param['is_config'] !== '') {
            $where[] = ['is_config', '=', $param['is_config']];
        }
        $configtpl = ChannelTpl::$config;
        $configlist = [];
        foreach ($configtpl as $k => $v) {
            if (isset($v['tob'])) {
                $top = $v['tob'];
                foreach ($top as $kk => $vv) {
                    $configlist[] = [
                        'cid' => $param['cid'],
                        'name' => $vv['tplname'],
                        'type' => $k,
                        'code' => $kk,
                        //'md' => time(),
                    ];
                }
            } else {
                if (isset($v['code']) && $v['code']) {
                    $configlist[] = [
                        'cid' => $param['cid'],
                        'name' => $v['tplname'],
                        'type' => $k,
                        'code' => $v['code'],
                        //'md' => time(),
                    ];
                }
            }
        }
        foreach ($configlist as $k => $v) {
            $info = ConfigChannel::instance()->info(['cid' => $v['cid'], 'code' => $v['code']]);
            if (empty($info)) {
                ConfigChannel::instance()->add($v);
            }
        }
        $list = ConfigChannel::instance()->listPages($where, $limit, $page);
        $count = ConfigChannel::instance()->countNum($where);
        $tpl = [];
        foreach ($list as &$item) {
            $tpl_type = $configtpl[$item['type']];
            $tpl = [];
            if ($tpl_type['value_type'] == 'json') {
                $item['value'] = json_decode($item['value'], true);
                if (!empty($tpl_type['tob']) && in_array($item['code'], array_keys($tpl_type['tob']))) {
                    $tpl = $tpl_type['tob'][$item['code']]['tpl'];
                } else  if(isset($tpl_type['tpl'])){
                    $tpl = $tpl_type['tpl'];
                }
                $value = '';
                foreach ($tpl as $titem) {
                    $val = isset($item['value'][$titem['key']]) ? $item['value'][$titem['key']] : '';                        
                    if (isset($titem['type']) && $titem['type']=='radio'&&$val!='') {
                        //$val= $titem['select'][0];
                        foreach ($titem['select'] as $kk=>$vv){                                
                            if ($item['value'][$titem['key']]==$kk) {
                                $val=$vv;
                                break;
                            }
                        }
                    }
                    $value .= "{$titem['view']} : {$val}<br/>";
                    $item['value'][$titem['key']] = [
                        'view' => $titem['view'],
                        'value' => $val,
                    ];
                }
            }
            $item['md'] = !empty($item['md']) ? date('Y-m-d H:i:s', $item['md']) : '';
            $item['type_name'] = ConfigChannel::instance()->type[$item['type']];
            $item['status_name'] = ConfigChannel::instance()->status[$item['status']];
            $item['is_config_name'] = ConfigChannel::instance()->is_config[$item['is_config']];
            $item['manager_name'] =$item['manager_id']?Manager::instance()->getFieldById($item['manager_id'],'name'):'';
            unset($item);
        }
        return Normal::returnCode(Normal::SUC, '获取成功',['list'=>$list,'total'=>$count]);
    }
    
    /**
     * 根据id获取配置项信息
     * @param array $param
     * @return array
     */
    public function getConfigById(array $param):array {
        if (empty($param['id'])) {
            return Normal::returnCode(Normal::FAIL, 'id必传');
        }
        if (empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'cid必传');
        }
        $configchannel = ConfigChannel::instance()->info(['id' => $param['id'], 'cid' => $param['cid']]);
        if (empty($configchannel)) {
            return Normal::returnCode(Normal::FAIL, '不存在该配置');
        }
        $configtpl = ChannelTpl::$config;
        $tpl_type = $configtpl[$configchannel['type']];
        if ($tpl_type['value_type'] == 'json') {//若配置内容为json
            $configchannel['value'] = json_decode($configchannel['value'], true)??[];
        }
        if (!empty($tpl_type['tob']) && in_array($configchannel['code'], array_keys($tpl_type['tob']))) {
            $tpl = $tpl_type['tob'][$configchannel['code']]['tpl'];
        } else {
            $tpl = $tpl_type['tpl'];
        }
        return Normal::returnCode(Normal::SUC,'获取成功',['tpl'=>$tpl,'config'=>$configchannel]);
    }
    
    /**
     * 根据id修改配置项信息
     * @param array $param
     * @return array
     */
    public function editChannelConfigById(array $param):array {
        if (empty($param['id'])) {
            return Normal::returnCode(Normal::FAIL, 'id必传');
        }
        if (empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'cid必传');
        }
        if (empty($param['value'])|| !is_array($param['value'])) {
            return Normal::returnCode(Normal::FAIL, '配置值必传货参数出错');
        }
        $infodata= $this->getConfigById($param);
        if($infodata['code']!= Normal::SUC){
            return $infodata;
        }
        $configvalue=[];
        $flag=true;
        foreach ($infodata['data']['tpl'] as $key => $value) {
            if(isset($param['value'][$value['key']])&&$param['value'][$value['key']]!==''){
                $configvalue[$value['key']]=$param['value'][$value['key']];
            }else{
                $flag=false;
            }
        }
        if($infodata['data']['config']['code']=='btb_buy'){
            if($param['value']['buy_type']==1){
                if(empty($param['value']['notice'])){
                    return Normal::returnCode(Normal::FAIL, '请输入提示文案');
                }
                if(mb_strlen($param['value']['notice'])>60){
                    return Normal::returnCode(Normal::FAIL, '提示文案60字以内');
                }
            }
        }
        if($infodata['data']['config']['code']=='wxmnapp_pay'){
            $mnapp['s_app_id']=$param['value']['appid']??'';
            $mnapp['s_appsecret']=$param['value']['appsecret']??'';
            $mnapp['app_id']=$param['value']['cappid']??'';
            $mnapp['appsecret']=$param['value']['cappsecret']??'';
            $mnapp['mch_id']=$param['value']['mch_id']??'';
            $mnapp['key']=$param['value']['key']??'';
            $mnapp['cert']=$param['value']['cert']??'';
            ChannelWx::instance()->edit(['cid'=>$param['cid']],$mnapp);
        }
        if($infodata['data']['config']['code']=='wxmp_pay'){
            $mnapp['mp_app_id']=$param['value']['appid']??'';
            $mnapp['mp_appsecret']=$param['value']['appsecret']??'';
            $mnapp['mp_mch_id']=$param['value']['mch_id']??'';
            $mnapp['mp_key']=$param['value']['key']??'';
            $mnapp['mp_cert']=$param['value']['cert']??'';
            ChannelWx::instance()->edit(['cid'=>$param['cid']],$mnapp);
        }
        $modifydata=[
            'value'=> json_encode($configvalue,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'manager_id'=>$param['manager_id'],
            'is_config'=>$flag?1:0,
            'md'=>time()
        ];
        $result= ConfigChannel::instance()->edit(['id'=>$param['id']], $modifydata);
        if($result){
            return Normal::returnCode(Normal::SUC,'操作成功');
        }else{
            return Normal::returnCode(Normal::FAIL,'操作失败');
        }
    }
    
    /**
     * 根据code获取配置
     * @param array $param
     * @return array
     */
    public function getConfigByCode(array $param):array {
        if (empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'cid必传');
        }
        if (empty($param['code'])) {
            return Normal::returnCode(Normal::FAIL, 'code必传');
        }
        $info = ConfigChannel::instance()->info(['cid' => $param['cid'], 'code' => $param['code']]);
        if (empty($info)) {
            $data=[];
        }
        $data=$info['value']?json_decode($info['value'],true):[];
        return Normal::returnCode(Normal::SUC,'获取成功',$data);
    }
}